import React, { Component } from 'react'
import moment from 'moment'
import { Link } from 'react-router-dom';
import axios from 'axios'
import { Spin, Modal,DatePicker,Button  } from 'antd';
import ReactEcharts from 'echarts-for-react';
import TweenOne from 'rc-tween-one';
import Children from 'rc-tween-one/lib/plugin/ChildrenPlugin';
import Warning from './warning'
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
require('./index.css')
const { MonthPicker } = DatePicker;
TweenOne.plugins.push(Children);

export default class ReportForm extends Component {

  constructor(props) {
    super(props)
    this.state = {
      incomeAnimation:null,
      numberAnimation:null,
      numberHotelAnimation:null,
      hotelIncomeAnimation:null,
      todayIncomeAnimation:null,
      secondaryAnimation:null,
      ticketDistributeNumTopFive:[],
      ticketDistributeIncomeTopFive:[],
      todayIncome:'',
      todayNum:'',
      hotelState:{},
      hotelData:{},
      consumptionNowData:[],
      distributorNum:[],
      distributorIncome:[],
      hotelIncome:'',
      isData:false,
      loading:true,
      hotelType:'income',
      ticketType:'income',
      consumpType:'income',
      hotelDistributeNumTopFive:[],
      hotelDistributeIncomeTopFive:[],
      consumptionDistributeNumTopFive:[],
      consumptionDistributeIncomeTopFive:[],
      warningList:[],
      dateString:moment().format("YYYY-MM").replace("-",""),
      consumptionIncome:''

    }
  }

  componentWillMount(){
    document.title = '景区报表中心'
    let _this=this;
    this.getData()
    setInterval(function(){
      _this.getData()
    },60000)
  }

  yourTarget(count){
    var i = count/10000;
    var decimal = count%10000/1000;
    var your_target =parseFloat( i + '.' + decimal);
    return your_target.toFixed(3)
  }

  formatNumber(value) {
    value += '';
    const list = value.split('.');
    const prefix = list[0].charAt(0) === '-' ? '-' : '';
    let num = prefix ? list[0].slice(1) : list[0];
    let result = '';
    while (num.length > 3) {
      result = `,${num.slice(-3)}${result}`;
      num = num.slice(0, num.length - 3);
    }
    if (num) {
      result = num + result;
    }
    return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
  }

  componentDidMount() {
  }

  getData(){
    axios.get(`http://sjhh.stswat.com:8180/app/MStatistics/getIndexData.do`,
    ).then(response => {
      let {hotelData,consumptionData,distributorIncome,distributorNum,nowData,ticketData,warningList} = response.data
      let {todayNum,todayIncome,hotelIncome,consumptionIncome} = nowData
      let {hotelDistributeIncome,hotelDistributeIncomeTopFive,hotelDistributeNum,hotelDistributeNumTopFive,hotelFiveData,hotelState} = hotelData
      let todayIncomes = parseInt(todayIncome) + parseInt(hotelIncome) + parseInt(consumptionIncome)
      let inHotel = (hotelState.hotel_6_total - hotelState.hotel_6_empty) + (hotelState.hotel_8_total - hotelState.hotel_8_empty)
      let {ticketDistributeIncome,ticketDistributeIncomeTopFive,ticketDistributeNum,ticketDistributeNumTopFive,ticketFiveData} = ticketData
      let {consumptionNowData,consumptionDistributeNumTopFive,consumptionDistributeNum,consumptionDistributeIncomeTopFive,consumptionDistributeIncome} = consumptionData
      this.setState({
        todayIncome,todayNum,ticketDistributeNumTopFive,ticketDistributeIncomeTopFive,hotelState,hotelData,consumptionNowData,distributorNum,distributorIncome,hotelIncome,hotelDistributeNumTopFive,consumptionDistributeNumTopFive,consumptionDistributeIncomeTopFive,hotelDistributeIncomeTopFive,warningList,consumptionIncome,
        isData:true,loading:false
      },()=>{
        this.setState({
          todayIncomeAnimation:{
            Children: { 
              value: parseInt(todayIncome),floatLength: 0,
            }, 
            duration: 1000,
          },
          secondaryAnimation:{
            Children: { 
              value: parseInt(consumptionIncome),floatLength: 0,
            }, 
            duration: 1000,
          },
          hotelIncomeAnimation:{
            Children: { 
              value: parseInt(hotelIncome),floatLength: 0,
            }, 
            duration: 1000,
          },
          incomeAnimation:{
            Children: { 
              value: parseInt(todayIncomes),floatLength: 0,
            }, 
            duration: 1000,
          },
          numberAnimation:{
            Children: { 
              value: parseInt(todayNum),floatLength: 0,
            }, 
            duration: 1000,
          },
          numberHotelAnimation:{
            Children: { 
              value: parseInt(inHotel),floatLength: 0,
            }, 
            duration: 1000,
          },
        })
      })

      //缓存

      localStorage.setItem('warningList',JSON.stringify(warningList))

      localStorage.setItem('hotelDistributeIncome',JSON.stringify(hotelDistributeIncome))
      localStorage.setItem('hotelDistributeNum',JSON.stringify(hotelDistributeNum))
      localStorage.setItem('hotelFiveData',JSON.stringify(hotelFiveData))

      localStorage.setItem('ticketDistributeIncome',JSON.stringify(ticketDistributeIncome))
      localStorage.setItem('ticketDistributeNum',JSON.stringify(ticketDistributeNum))
      localStorage.setItem('ticketFiveData',JSON.stringify(ticketFiveData))

      localStorage.setItem('consumptionDistributeIncome',JSON.stringify(consumptionDistributeIncome))
      localStorage.setItem('consumptionDistributeNum',JSON.stringify(consumptionDistributeNum))
      localStorage.setItem('consumptionNowData',JSON.stringify(consumptionNowData))
    }).catch(error => {
    })
  }

  /** 
  * js数组排序 支持数字和字符串
  * @param params
  * @param arrObj   obj     必填  数组对象
  * @param keyName  string  必填  要排序的属性名称
  * @param type     int     选填  默认type:0 正顺  type:1反顺
  */
  arrItemSort(arrObj,keyName,type) {
    //这里如果 直接等于arrObj，相当于只是对对象的引用，改变排序会同时影响原有对象的排序，而通过arrObj.slice(0)，
    //表示把对象复制给另一个对象，两者间互不影响 
    var tempArrObj = arrObj.slice(0);
    var compare = function (keyName,type) {
        return function (obj1, obj2) {
            var val1 = obj1[keyName];
            var val2 = obj2[keyName];
            if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
                val1 = Number(val1);
                val2 = Number(val2);
                }
                //如果值为空的，放在最后       
                if (val1 === null && val2 === null) {
                return 0;
            } else if (val1 == null && val2!= null ) {
                return (type===1 ? -1 : 1);
            } else if (val2 === null && val1!= null ) {
                return (type===1 ? 1 : -1);
            }            
                //排序
            if (val1 < val2) {
                return (type===1 ? 1 : -1);
            } else if (val1 > val2) {
                return (type===1 ? -1 : 1);;
            } else {
                return 0;
            }            
        } 
    }
    return tempArrObj.sort(compare(keyName,type));
  }


  getTicketOption(type,channel){
    let topFiveList = ''//hotelDistributeNumTopFive,consumptionDistributeNumTopFive,consumptionDistributeIncomeTopFive,hotelDistributeIncomeTopFive,
    if(channel === 'ticket'){
      topFiveList = type === 'FiveNum' ? this.state.ticketDistributeNumTopFive  : this.state.ticketDistributeIncomeTopFive
    }else if(channel === 'hotel'){
      topFiveList = type === 'FiveNum' ? this.state.hotelDistributeNumTopFive  : this.state.hotelDistributeIncomeTopFive
    }else if(channel === 'consumption'){
      console.log(this.state.consumptionDistributeNumTopFive)
      topFiveList = type === 'FiveNum' ? this.state.consumptionDistributeNumTopFive  : this.state.consumptionDistributeIncomeTopFive
    }
    console.log(topFiveList)
    // topFiveList =  this.arrItemSort(topFiveList,'value',1) //重新排序
    return {
      tooltip : {
          trigger: 'item',
          formatter: "{b} : {c} ({d}%)",
          position:['30%',70],
          textStyle:{
            fontSize:10
          }
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        data:(function (){
          var res = [];
          var len = topFiveList.length;
          for(let i=0;i<len;i++){
            res.push(topFiveList[i]['name'])
          }
          return res
        })(),
        itemWidth:10,
        itemHeight:5,
        formatter: function (params) {   
            let n = topFiveList.length
            for(let i=0;i<n;i++){
              if(topFiveList[i]['name'] === params){
                return `${params}  ${topFiveList[i]['value']} ${type === 'FiveNum' ? (channel === 'hotel' ? '间' : '张'):'元'}`
              }
            }
        }, 
        textStyle:{
          fontSize:10
        }
      },
      series : [
        {
          name: '',
          type: 'pie',
          radius : '72%',
          center: ['78%', '50%'],
          data:topFiveList,
          label:{
            fontSize:9
          },
          itemStyle: {
            emphasis: {
                shadowBlur: 8,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            normal: {
              color: function(params) {
                  var colorList = [
                    '#2ec77e','#49e1eb','#90d420','#e6c515','#f08c60',
                    '#b096e8'
                  ];
                  return colorList[params.dataIndex]
              },
              label: {
                  show: false,
                  position: 'top',
                  fontSize:9,
                  formatter: '{b}\n{c}({d}%)'
              }
            }
          },
          emphasis:{
            label:{
              fontSize:10
            }
          }
        }
      ]
    }
  }


  getHotelOption(){
    let {hotel_6_empty,hotel_6_total,hotel_8_empty,hotel_8_total} = this.state.hotelState
    let hotel_6_in = hotel_6_total - hotel_6_empty
    let hotel_8_in = hotel_8_total - hotel_8_empty

    var titlename = ['养心苑', '青春驿站'];
    var valdata = [`${hotel_6_in}/${hotel_6_total}`, `${hotel_8_in}/${hotel_8_total}`]
    return {
      backgroundColor: '#fff',
      grid: {
          left: '24%',
          top:'2%',
          right: '18%',
          bottom: '2%',
          containLabel: false,
      },
      xAxis: {
        type: 'value',
        max: [hotel_6_total,hotel_8_total],
        splitLine: {
            show: false
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            show: false
        },
        axisTick: {
            show: false
        }
      },
      yAxis: [
        {
          show: true,
          data: titlename,
          inverse: true,
          axisLine: {
              show: false
          },
          splitLine: {
              show: false
          },
          axisTick: {
              show: false
          },
          axisLabel: {
            show:true,
            color: '#707070',
            textStyle:{
              fontSize:15,
              
            },
            formatter: function(value, index) {
                return [
                    value
                ].join('\n')
            },
          },
        }, 
        {
          show: true,
          inverse: true,
          data: valdata,
          axisLabel: {
              textStyle: {
                  fontSize: 13,
                  fontWeight:'bolder',
                  color: '#707070',
              },
              formatter: function(value, index) {
                return  [ `{a|${value.split('/')[0]}}/{b|${value.split('/')[1]}}`].join('\n')
              },
              rich: {
                a: {
                    color: '#31c497',
                    fontSize: 14,
                    fontWeight:'bolder'
                },
                b: {
                  fontSize: 13,
                  fontWeight:'bolder',
                  color:'#707070'
                },
              }
          },
          axisLine: {
              show: false
          },
          splitLine: {
              show: false
          },
          axisTick: {
              show: false
          },
      
      }],
    series: [
        { //间距
            type: 'bar',
            barWidth: 16,
            stack: 'b',
            legendHoverLink: false,
            itemStyle: {
                normal: {
                    color: 'rgba(0,0,0,0)'
                }
            },
            data: [0.8,0.8]
        },
        { //内
          type: 'bar',
          barWidth: 16,
          stack: 'b',
          label: {
              normal: {
                  show: false,
                  position: 'inside',
                  textStyle: {
                      color: '#fff'
                  },
                  formatter: '{c}%'
              }
          },
          legendHoverLink: false,
          silent: true,
          itemStyle: {
            normal: {
                barBorderRadius: 16,
                color: {
                  colorStops: [{
                    offset: 0,
                    color: '#31c497' // 0% 处的颜色
                }, {
                    offset: 1,
                    color: '#53deff' // 100% 处的颜色641118183@qq.com
                }],
                }
            }
          },
          data: [(hotel_6_in*100)/hotel_6_total,(hotel_8_in*100)/hotel_8_total]
        },
        { //框
          type: 'bar',
          barWidth: 20,
          barGap: '-112%',
          label: {
            normal: {
                show: false,

                position: 'right',
                textStyle: {
                    color: '#000'
                }
            }
          },
          itemStyle: {
              normal: {
                  backgroundColor:'#e6e6e6',
                  barBorderRadius: 20,
                  color: '#e6e6e6', //底色
              }
          },
          data: [100,100],
          z: 1,
        }
      ]
    }
  }

  html(){
    let {consumptionNowData,todayIncome,hotelIncome,todayNum,hotelDistributeNumTopFive,ticketDistributeNumTopFive,consumptionDistributeNumTopFive,warningList,consumptionIncome} = this.state
    let isConsumption = false
    consumptionNowData.map((item, index) => {
      parseInt(item.totalIncome) > 0 && (isConsumption = true)
    })
    let htmlData = []
    htmlData.push(
      <div className="ReportBox" style={warningList.length>0?{margin:'64px auto 0'}:null}>
        <div className="ReportItem clearfix boxS pad15 bgfff">
          <div className="tex-fs mr-16">
            <div className="clearfix">
              <p className="flof fs18-fw col70">今日收入</p>
              <p className="flor fs18-fw col70 fs-15">{moment().format('YYYY-MM-DD')}</p>
            </div>
            <p className="mrb-16">
            {
              parseInt(todayIncome)>0?
              <p className="price">
              <TweenOne animation={this.state.incomeAnimation} className="price fs32 " style={{display: "-webkit-inline-box"}}></TweenOne>
              <span className="fs-10 clor1"> 元</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }</p>
          </div>
          <div class="ReportItemLeft bord-r pos-rel " onClick={()=>{this.props.history.push(`/BarREcharts/fiveDays/null`)}}>
            <p className="fs-15 col9b">门票</p>
            {
              parseInt(todayIncome)>0?
              <p className="price">
              <TweenOne animation={this.state.todayIncomeAnimation} className="price" style={{display: "-webkit-inline-box"}}></TweenOne>
              <span className="fs-10 clor1"> 元</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
          <div class="ReportItemLeft bord-r" onClick={()=>{this.props.history.push(`/BarREcharts/fiveDays/null`)}}>
            <p className="fs-15 col9b">酒店</p>
            {
              parseInt(hotelIncome)>0?
              <p className="price">
                <TweenOne animation={this.state.hotelIncomeAnimation} className="price " style={{display: "-webkit-inline-box"}}></TweenOne>
                <span className="fs-10 clor1"> 元</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
          <div class="ReportItemRight" onClick={()=>{this.props.history.push(`/BarREcharts/fiveDays/null`)}}>
            <p className="fs-15 col9b">二次消费</p>
            {
              parseInt(consumptionIncome)>0?
              <p className="price">
                <TweenOne animation={this.state.secondaryAnimation} className="price " style={{display: "-webkit-inline-box"}}></TweenOne>
                <span className="fs-10 clor1"> 元</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
        </div>

        <div className="ReportItem clearfix boxS pad15 bgfff pad-16">
            <p className="flof mr-fs col70 fw-nor">今日入园</p>
          <div class="flor mar-10">
            {
              parseInt(todayNum)>0?
              <p className="price">
                <TweenOne animation={this.state.numberAnimation} className="price col30" style={{display: "-webkit-inline-box"}}></TweenOne>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
        </div>

        <div className="ReportItem clearfix boxS pad15 bgfff pad-16">
            <p className="flof mr-fs col70 fw-nor">入住间数</p>
          <div class="flor mar-10">
            {
              parseInt(todayNum)>0?
              <p className="price">
                <TweenOne animation={this.state.numberHotelAnimation} className="price col30" style={{display: "-webkit-inline-box"}}></TweenOne>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
        </div>

        <div className="ReportItem clearfix boxS pad15 bgfff pad10">
          { hotelDistributeNumTopFive.length>0 ?
          <div className="mr-10 clearfix">
            <ReactEcharts
              ref = ""
              style={{height:80,width:'100%'}}
              option={this.getHotelOption()}
              notMerge={true}
              lazyUpdate={true}
              theme={"theme_name"}
            />
          </div>
          :<div className="mr-texc colb3">暂无统计数据</div>}
        </div>

        <div className="ReportItem clearfix boxS pad100 pos-rel bgfff" style={{}}>
          <p className="te-left clearfix hotelTitle">
            <div className={this.state.ticketType === 'income'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({ticketType:'income'})}}>门票收入</div>
            <div className={this.state.ticketType === 'FiveNum'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({ticketType:'FiveNum'})}}>门票销量</div>
            {ticketDistributeNumTopFive.length>0&&<Link to={`BarREcharts/rankings/ticket`} className="pos-abs more flor">查看更多</Link>}
          </p>
          { 
            ticketDistributeNumTopFive.length>0 ?
            <div className="mar50">
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getTicketOption(this.state.ticketType,'ticket')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            </div>:<div className="mr-texc colb3">暂无统计数据</div>
          }
        </div>

        <div className="ReportItem clearfix boxS pad100 pos-rel bgfff" style={{}}>
          <p className="te-left clearfix hotelTitle">
            <div className={this.state.hotelType === 'income'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({hotelType:'income'})}}>酒店收入</div>
            <div className={this.state.hotelType === 'FiveNum'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({hotelType:'FiveNum'})}}>酒店销量</div>
            {hotelDistributeNumTopFive.length>0&&<Link to={`BarREcharts/rankings/hotel`} className="pos-abs more flor">查看更多</Link>}
          </p>
          
          { 
            hotelDistributeNumTopFive.length>0 ?
            <div className="mar50">
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getTicketOption(this.state.hotelType,'hotel')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            </div>:<div className="mr-texc colb3">暂无统计数据</div>
          }
        </div>

        <div className="ReportItem clearfix boxS pad100 pos-rel bgfff" style={{}}>
          <p className="te-left clearfix hotelTitle">
            <div className={this.state.consumpType === 'income'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({consumpType:'income'})}}>二销收入</div>
            <div className={this.state.consumpType === 'FiveNum'?'titleSelect flof pad5-10 ':'flof pad5-10 '} onClick={()=>{this.setState({consumpType:'FiveNum'})}}>二销销量</div>
            {consumptionDistributeNumTopFive.length>0&&<Link to={`BarREcharts/rankings/consumption`} className="pos-abs more flor">查看更多</Link>}
          </p>
            
          { 
            consumptionDistributeNumTopFive.length>0 ?
            <div className="mar50">
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getTicketOption(this.state.consumpType,'consumption')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            </div>:<div className="mr-texc colb3">暂无统计数据</div>
          }
        </div>


        { 
          isConsumption&&<div className="ReportItem clearfix boxS pad15 bgfff" style={{padding:'8px 0 0 0'}}>
            <p className="te-cen ">二次消费项目每日预订/收入/排队人数</p>
            <div className="mr-10">
              <p className='tableHear clearfix tableHearFs' >
                <span class="erName"></span>
                <span>已售</span>
                <span>收入</span>
                <span>排队人数</span>
              </p>
              {
                consumptionNowData.map((item, index) => (
                  parseInt(item.totalIncome) > 0 ? <p className='tableHear clearfix '>
                    <span class="erName">{item.consumptionName.length>5?`${item.consumptionName.substr(0, 5)}..`:item.consumptionName}<i className="ericon">|</i></span>
                    <span>{item.totalNum}</span>
                    <span>{item.totalIncome}</span>
                    <span>{item.lineNum}</span>
                  </p>:null
                ))
              }
            </div>
          </div>
        }
      </div>
    )
    return htmlData
  }

  handleOk = () => {
    setTimeout(() => {
      this.setState({ loading: false, visible: false });
    }, 600);
  }

  handleCancel = () => {
    this.setState({ visible: false });
  }

  onChange(date, dateString) {
    this.setState({dateString:dateString.replace("-","")})
  }

  disabledDate(current) {
    // Can not select days before today and today
    return current && current > moment().endOf('day');
  }

  exportReport(){
    window.location.href = `http://sjhh.stswat.com:8180/app/MStatistics/doExport.do?startDate=${this.state.dateString}`
    this.setState({visible:false})
  }

  render() {
    let {isData} = this.state
    return (
      <div style={{ marginBottom: 20 }} id="bg">
        {isData&&<Warning />}
        <Spin spinning={this.state.loading} style={{width:'100%',position: 'fixed',top: '48%'}} />
        {isData&&this.html()}
        {isData&&
          <div className="exportBut" onClick={()=>{this.setState({visible:true})}}>导出报表</div>
        }
        <Modal
          title="导出报表"
          visible={this.state.visible}
          closable={false}
          maskClosable={true}
          footer={null}
          onOk={this.handleOk}
          bodyStyle={{ padding: 4 }}
          onCancel={this.handleCancel}
        >
          <div>
            <div style={{margin:'20px 0',textAlign: 'center'}}>
              <MonthPicker onChange={this.onChange.bind(this)} defaultValue={moment(moment().format("YYYY-MM"), 'YYYY-MM')} disabledDate={this.disabledDate} style={{width:'60%'}} placeholder="选择导出报表月份" />
              <Button type="primary" icon="download" size={'large'} style={{height:30,marginLeft:10,width:'30%',background:'#31c497',borderColor:'#31c497'}} onClick={this.exportReport.bind(this)} >导出</Button>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}
